//
//  RecommendCycleView.swift
//  SwiftDemo
//
//  Created by liguoqing on 2022/6/27.
//  Copyright © 2022 guoqing.li. All rights reserved.
//

import UIKit

private let kCycleViewCellID = "CycleViewCellID"

class RecommendCycleView : UIView {
    // lazyload
    lazy var collectionView: UICollectionView = { [unowned self] in
        let layout = UICollectionViewFlowLayout();
        layout.itemSize = CGSize(width: kScreenW, height: kScreenW * 3/8);
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0;
        layout.scrollDirection = .horizontal
        
        let collectionView = UICollectionView.init(frame: .zero, collectionViewLayout: layout);
        collectionView.delegate = self;
        collectionView.dataSource = self;
        collectionView.isPagingEnabled = true
        collectionView.register(RecommentCycleViewCell.self, forCellWithReuseIdentifier: kCycleViewCellID)
        return collectionView
    }()
    
    lazy var pageControl: UIPageControl = {
        let pageControl = UIPageControl()
        pageControl.pageIndicatorTintColor = .lightGray
        pageControl.currentPageIndicatorTintColor = .orange
        return pageControl
    }()
    // 属性
    var cycleTimer : Timer?
    var cycleModels : [CycleModel]? {
        didSet{
            // 刷新数据
            collectionView.reloadData()
            // 更新pageCount
            pageControl.numberOfPages = cycleModels?.count ?? 0
            // 滚动到中间位置
//            let indexPath = NSIndexPath.init(item: cycleModels?.count ?? 0 * 10, section: 0)
//            collectionView.scrollToItem(at: indexPath as IndexPath, at: .left, animated: false)
            // 移除定时器
            removeTimer()
            addTimer()
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension RecommendCycleView
{
    private func setupUI(){
        addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.edges.equalTo(0)
        }
        addSubview(pageControl)
        pageControl.snp.makeConstraints { make in
            make.right.equalTo(0);
            make.bottom.equalTo(-5)
        }
    }
}

extension RecommendCycleView : UICollectionViewDataSource
{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return cycleModels?.count ?? 0
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kCycleViewCellID, for: indexPath) as! RecommentCycleViewCell
//        let cycleModel = cycleModels![indexPath.item % cycleModels!.count]
        cell.cycleModel = cycleModels?[indexPath.item]
        return cell
    }
}

extension RecommendCycleView :UICollectionViewDelegate
{
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
    }
}


extension RecommendCycleView : UIScrollViewDelegate
{
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        
        //1. 获取滚动的偏移量
        let offsetX = scrollView.contentOffset.x + scrollView.bounds.width * 0.5
        
        //2. 计算 pageControl 的 currentIndex
        pageControl.currentPage = Int(offsetX / scrollView.bounds.width) % (cycleModels?.count ?? 1)
        
    }
    
    // 监听用户拖拽
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        
        removeTimer()
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        
        addTimer()
    }
}

extension RecommendCycleView
{
    private func addTimer () {
        cycleTimer = Timer(timeInterval: 3.0, target: self, selector: #selector(addCycleTimer), userInfo: nil, repeats: true)
        RunLoop.main.add(cycleTimer!, forMode: .common)
    }
    
    private func removeTimer () {
        cycleTimer?.invalidate()
        cycleTimer = nil
    }
    
    @objc private func addCycleTimer (){
        let currentOffsetX = collectionView.contentOffset.x;
        
        var offsetX = currentOffsetX + collectionView.bounds.width;
        
        
        let maxOffsetX =  CGFloat(cycleModels?.count ?? 0) * collectionView.bounds.width;
        
        if (offsetX == maxOffsetX){
            offsetX = 0.0
        }
        
        print("currentOffsetX -- \(offsetX)")
        
        collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false)
    }
}
